package com.hyty.cordova.plugins;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.hyty.cordova.imagepicker.Album;
import com.hyty.cordova.imagepicker.AlbumFile;
import com.hyty.cordova.imagepicker.api.widget.Widget;
import com.hyty.cordova.plugins.bean.Config;
import com.hyty.cordova.plugins.bean.PreviewDataBean;
import com.hyty.cordova.takecamera.TakeCameraActivity;
import com.hyty.cordova.util.Log;
import com.hyty.cordova.util.PermissionUtil;
import com.hyty.cordova.util.Utils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import static com.hyty.cordova.util.Utils.CheckParams;

/**
 * ================================================================
 * 创建时间：2017/12/18 11:41
 * 创建人：赵文贇
 * 文件描述：插件的入口类
 * 看淡身边的虚伪，静心宁神做好自己。路那么长，无愧走好每一步。
 * ================================================================
 */
public class MultiMediaPlugin extends CordovaPlugin {
    private Config mConfig;
    private static Activity mActivity;
    public static MultiMediaPlugin mPlugin;// TODO: 2017/12/18 测试、正式版本需要注释/反注释的代码  ----------  1

    // TODO: 2017/12/18 测试、正式版本需要注释/反注释的代码  ----------  2
    public static MultiMediaPlugin getInstance(Activity mActivity1) {
        mActivity = mActivity1;
        if (mPlugin == null) mPlugin = new MultiMediaPlugin();
        return mPlugin;
    }

    /**
     * 程序入口函数，首先会执行到这里。还有两个入口函数直接return了false
     *
     * @param action          程序的action
     * @param rawArgs         参数
     * @param callbackContext 用来给H5回调的接口
     * @return 插件执行结果
     * @throws JSONException 捕获的异常
     */
    @Override
    public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
        //获取参数
        mConfig = CheckParams(rawArgs);

        //检查参数
        if (mConfig == null ||
                mConfig.getType() == 0
                || TextUtils.isEmpty(mConfig.getFolderName())) {
            Log.e("传入的参数有误，type、folderName字段任何业务类型下均不能为空");
            return false;
        }
//        mActivity = cordova.getActivity();// TODO: 2017/12/18 测试、正式版本需要注释/反注释的代码  ----------  3
        //获取相关权限
        Observable.create(e -> e.onNext("")).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(mO -> requestPermissions());//请求权限

        return true;
    }

    /**
     * 权限获取
     */
    private void requestPermissions() {
        PermissionUtil.requestPermission(new PermissionUtil.RequestPermission() {
                                             @Override
                                             public void onRequestPermissionSuccess() {

                                                 //初始化文件系统
                                                 Utils.initFileSystem(mConfig.getFolderName());

                                                 //初始化图片加载器
                                                 Utils.initImageLoder(mActivity);

                                                 //业务分类chuli
                                                 xxoo();
                                             }

                                             @Override
                                             public void onRequestPermissionFailure() {
                                                 Toast.makeText(mActivity, "权限获取失败，请手动授权", Toast.LENGTH_SHORT).show();
                                             }
                                         }, new RxPermissions(mActivity), RxErrorHandler
                        .builder()
                        .with(mActivity)
                        .responseErrorListener((context, t) -> Log.e("异常"))
                        .build(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
        );
    }

    /**
     * 主要的业务逻辑在这里
     */
    private void xxoo() {
        switch (mConfig.getType()) {
            case 1:
                //快速拍照
                Log.d("快速拍照");
                mActivity.startActivity(new Intent(mActivity, TakeCameraActivity.class));
                break;
            case 2:
                //多图选择
                Log.d("多图选择");
                selectAlbum();
                break;
            case 3:
                //图片预览
                Log.d("图片预览");
                previewImages();
                break;
            case 4:
                //快速录像
                Log.d("快速录像");

                break;
        }
    }


    private void selectAlbum() {
        AlbumFile mAlbumFile = new AlbumFile();
//        mAlbumFile.setPath();
        Album.image(mActivity)
//                Album.album(mActivity) //多媒体选择
                .multipleChoice()
                .requestCode(200)
                .columnCount(3)
                .selectCount(10)
                .camera(false)
//                .cameraVideoQuality(1)    //多媒体选择
//                .cameraVideoLimitDuration(Integer.MAX_VALUE) //多媒体选择
//                .cameraVideoLimitBytes(Integer.MAX_VALUE) //多媒体选择
                .checkedList(null)
                .widget(
                        Widget.newDarkBuilder(mActivity)
                                .title("图片选择")
                                .build()
                )
                .onResult((requestCode, result) -> {
                    Log.d("requestCode:" + requestCode);
                    StringBuilder mStringBuffer = new StringBuilder();
                    for (int i = 0; i < result.size(); i++) {
                        mStringBuffer.append(result.get(i).toString()).append("\n\n\n");
                    }
                    Log.d("result:\n" + mStringBuffer.toString());
                })
                .onCancel((requestCode, result) -> {
                    Log.d("requestCode:" + requestCode);
                    Log.d("result:" + result);
                })
                .start();
    }

    private void previewImages() {
        ArrayList<String> imageList = new ArrayList<>();
        for (PreviewDataBean mBean : mConfig.getPreviewDataList()) {
            imageList.add(Config.FILE_SAVED_PATH + mConfig.getFolderName() + "/" + mBean.getFilePath());
        }

//        Collections.addAll(imageList, IMAGE_PATH_LIST);

        Album.gallery(mActivity)
                .requestCode(200)
                .checkedList(imageList)
                .navigationAlpha(80)
                .checkable(mConfig.isCanDelete())
                .widget(
                        Widget.newDarkBuilder(mActivity)
                                .title("图片预览")
                                .build()
                )
                .onResult((requestCode, result) -> {
                    Log.d("requestCode:" + requestCode);
                    StringBuilder mStringBuffer = new StringBuilder();
                    for (int i = 0; i < result.size(); i++) {
                        mStringBuffer.append(result.get(i).toString()).append("\n\n\n");
                    }
                    Log.d("result:\n" + mStringBuffer.toString());
                })
                .start();
    }

//    private void initFFmpeg() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                File fileAppRoot = new File(
//                        getApplicationInfo().dataDir);
//                try {
//                    fc = new FfmpegController(
//                            context, fileAppRoot);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

}
